package com.nongcai159.mall.lib_common.http

import com.google.gson.GsonBuilder
import com.jakewharton.retrofit2.adapter.kotlin.coroutines.experimental.CoroutineCallAdapterFactory
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

/**
 * 网络请求
 *
 *
 * Created by tanbiheng on 2017/9/19.
 */

class RetrofitManager private constructor() {
    private var mRetrofit: Retrofit? = null

    private object RetrofitHolder {
        val INSTANCE = RetrofitManager()
    }

    init {
        val gson = GsonBuilder()
                .setLenient()// json宽松
                .enableComplexMapKeySerialization()//支持Map的key为复杂对象的形式
                .serializeNulls() //智能null
                .setPrettyPrinting()// 调教格式
                .disableHtmlEscaping() //默认是GSON把HTML转义的
                .create()

        // 创建Retrofit
        mRetrofit = Retrofit.Builder()
                .client(OkHttpManager.instance!!.getOkHttpClient())
                .addCallAdapterFactory(CoroutineCallAdapterFactory())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl("")
                .build()
    }

    /**
     * 获取对应的Service
     *
     * @param service Service 的 class
     * @param <T>
     * @return
    </T> */
    fun <T> create(service: Class<T>): T {
        return mRetrofit!!.create(service)
    }

    companion object {

        /**
         * 获取RetrofitManager
         *
         * @return
         */
        val instance: RetrofitManager
            get() = RetrofitHolder.INSTANCE
    }
}
